import { decode } from "./base64-arraybuffer";

export const formatTime = (date, isSecond = true) => {
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    if (isSecond) {
        return [hour, minute, second].map(formatNumber).join(":");
    } else {
        return [hour, minute].map(formatNumber).join(":");
    }
};

export const formatDate = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return [year, month, day].map(formatNumber).join("-");
};

export const formatDateTime = (date, isSecond = true) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    if (isSecond) {
        return [year, month, day].map(formatNumber).join("-") + " " + [hour, minute, second].map(formatNumber).join(":");
    } else {
        return [year, month, day].map(formatNumber).join("-") + " " + [hour, minute].map(formatNumber).join(":");
    }
};

const formatNumber = (n) => {
    const s = n.toString();
    return s[1] ? s : "0" + s;
};

export function genNonDuplicateID(randomLength) {
    return Number(Math.random().toString().substr(3, randomLength) + Date.now())
        .toString(36)
        .toUpperCase();
}

export function getParam(str, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = str.split("?")[1].match(reg); //匹配目标参数
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return null; //返回参数值
}

// 获取参数
export function getURLSearchParams(option, key) {
    if (option.q) {
        const q = decodeURIComponent(option.q);
        return getParam(q, key);
    }
    return decodeURIComponent(option[key] || "");
}

export function systemInfo(callback) {
    wx.getNetworkType({
        success(res) {
            const info = wx.getSystemInfoSync();
            callback({
                ...info,
                networkType: res.networkType
            });
            // networkType 网络
            // model 设备型号
            // system 操作系统及版本
        }
    });
}

export function uuid() {
    if (wx.getStorageSync("uuid")) {
        return wx.getStorageSync("uuid");
    }

    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    wx.setStorageSync("uuid", uuid);
    return uuid;
}

export function formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "");
        match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "");
        match = match.replace(/height="[^"]+"/gi, "").replace(/height='[^']+'/gi, "");

        // match = match.replace(/<img/gi,'<img show-menu-by-longpress="{{true}}"')

        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
        match = match.replace(/width:[^;]+;/gi, "max-width:100%;").replace(/width:[^;]+;/gi, "max-width:100%;");
        return match;
    });
    var newStyle = "margin:1em 0;";
    var pattern = /style="([^"]*)"/;

    newContent = newContent.replace(/<p[^>]*>/gi, function (str, capture) {
        // console.log(match);

        // return match÷
        // 匹配双引号内的内容
        var match = pattern.exec(str);

        if (match) {
            // 获取原始样式
            var originalStyleText = match[1];
            // 合并原始样式和新样式
            var mergedStyle = originalStyleText.trim().concat(" ", newStyle);
            // 替换原始样式
            var newStr = str.replace(pattern, 'style="' + mergedStyle + '"');
            // 输出替换后的字符串
            return newStr;
        } else {
            // 如果没有匹配到原始样式，直接添加新样式
            var newStr = str.replace("<p ", '<p style="' + newStyle + '" ');
            // console.log(newStr);
            return newStr;
        }
    });

    newContent = newContent.replace(/<p>/gi, function (str, capture) {
        var newStr = str.replace("<p>", '<p style="' + newStyle + '" >');
        return newStr;
    });
    // var match = pattern.exec(str);
    // newContent = newContent.replace(/<p[^>]*>/gi, function (match, capture) {
    //   match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    //   return match
    // })
    // newContent = newContent.replace(/<p/g, '<p style="margin:1em 0"')
    // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
}

export function urlParamEncode(param) {
    if (param == null) return "";
    var arr = [];
    for (var p in param)
        if (param.hasOwnProperty(p)) {
            arr.push(encodeURIComponent(p) + "=" + encodeURIComponent(param[p]));
        }
    return arr.join("&");
}

export function postFormatTime(timestamp) {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentDate = now.getDate();
    const yesterday = new Date(new Date().setDate(currentDate - 1));

    const dt = new Date(timestamp);
    const delta = now - dt;

    if (delta < 86400000 && dt.getDate() === currentDate) {
        return `${dt.getHours()}:${dt.getMinutes()}`;
    } else if (dt.getDate() === yesterday.getDate()) {
        return "昨天";
    } else if (dt.getFullYear() === currentYear) {
        return `${dt.getMonth() + 1}-${dt.getDate()}`;
    } else {
        return `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`;
    }
}

export function base64src(base64data, cb) {
    const fsm = wx.getFileSystemManager();
    const FILE_BASE_NAME = "tmp_base64src"; //自定义文件名
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
    if (!format) {
        return new Error("ERROR_BASE64SRC_PARSE");
    }
    const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
    const buffer = decode(bodyData);
    fsm.writeFile({
        filePath,
        data: buffer,
        encoding: "binary",
        success() {
            cb(filePath);
        },
        fail() {
            return new Error("ERROR_BASE64SRC_WRITE");
        }
    });
}
